package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Keyword;
import com.ywgt.service.KeywordService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin/keyword")
@ApiModel("关键词管理")
public class KeywordController {
    @Autowired
    KeywordService keywordService;

    /**
     *   page: 1,
     *         limit: 20,
     *         keyword: undefined,
     *         url: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getKeywords(String keyword,@RequestParam(required = false,defaultValue = "add_time") String sort,
                              @RequestParam(required = false,defaultValue = "desc") String order,
                              @RequestParam(required = false,defaultValue = "1") int page,
                              @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Keyword> keywords=keywordService.getKeywords(keyword,page,limit,sort,order);
        List<Keyword> items = keywords.getResult();
        long total = keywords.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("items",items);
        data.put("total",total);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/update")
    public Object update(@RequestBody Keyword keyword){
        if(keywordService.updateById(keyword)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/create")
    public Object create(@RequestBody Keyword keyword){
        if(keywordService.save(keyword)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Keyword keyword){
        if(keywordService.removeById(keyword.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
